import { useState, useEffect, useRef } from 'react';
import {
  Layout,
  Table,
  Pagination,
  Row,
  Col,
  Spin,
  Image,
  Input,
  Descriptions,
  message,
  Cascader,
  Button,
  Form,
  Modal,
} from 'antd';
import { Link } from 'react-router-dom';
import {
  MinusCircleOutlined,
  PlusCircleOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  DeleteOutlined,
  SnippetsOutlined,
} from '@ant-design/icons';
import { Content, Header } from 'antd/lib/layout/layout';
import axios from 'axios';
import Config from '../../Config';
import { XKLYmap, JFKMmap, XZmap, SYFXmap, GXMSmap } from '../../Config';
import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import PizZipUtils from 'pizzip/utils/index.js';
import { saveAs } from 'file-saver';
import * as moment from 'moment';
import { useSelector } from 'react-redux';
import { selectUser } from '../../redux/Slice/userSlice';
import XLSX from 'xlsx';
import { openDownloadDialog, sheet2blob } from '../../utils/excel';
import InstrumentCard from '../InstrumentCard';

function loadFile(url, callback) {
  PizZipUtils.getBinaryContent(url, callback);
}
const options = [
  {
    label: '仪器名称',
    value: 1,
    children: [
      {
        label: '等于',
        value: 1,
      },
      {
        label: '包括',
        value: 2,
      },
      {
        label: '前匹配',
        value: 3,
      },
      {
        label: '后匹配',
        value: 4,
      },
    ],
  },
  {
    label: '仪器编号',
    value: 2,
    children: [
      {
        label: '等于',
        value: 1,
      },
      {
        label: '不等于',
        value: 2,
      },
      {
        label: '大于',
        value: 3,
      },
      {
        label: '大于等于',
        value: 4,
      },
      {
        label: '小于',
        value: 5,
      },
      {
        label: '小于等于',
        value: 6,
      },
    ],
  },
  {
    label: '金额',
    value: 3,
    children: [
      {
        label: '等于',
        value: 1,
      },
      {
        label: '不等于',
        value: 2,
      },
      {
        label: '大于',
        value: 3,
      },
      {
        label: '大于等于',
        value: 4,
      },
      {
        label: '小于',
        value: 5,
      },
      {
        label: '小于等于',
        value: 6,
      },
    ],
  },
  {
    label: '收费标准',
    value: 4,
    children: [
      {
        label: '等于',
        value: 1,
      },
      {
        label: '不等于',
        value: 2,
      },
      {
        label: '大于',
        value: 3,
      },
      {
        label: '大于等于',
        value: 4,
      },
      {
        label: '小于',
        value: 5,
      },
      {
        label: '小于等于',
        value: 6,
      },
    ],
  },
  {
    label: '批量',
    value: 5,
    children: [
      {
        label: '等于',
        value: 1,
      },
      {
        label: '不等于',
        value: 2,
      },
      {
        label: '大于',
        value: 3,
      },
      {
        label: '大于等于',
        value: 4,
      },
      {
        label: '小于',
        value: 5,
      },
      {
        label: '小于等于',
        value: 6,
      },
    ],
  },
  {
    label: '共享模式',
    value: 6,
    children: [
      {
        label: '外部共享',
        value: 1,
      },
      {
        label: '内部共享',
        value: 2,
      },
      {
        label: '不共享',
        value: 3,
      },
    ],
  },
  {
    label: '现状',
    value: 7,
    children: [
      {
        label: '在用',
        value: '1',
      },
      {
        label: '闲置',
        value: '2',
      },
      {
        label: '毁坏不能用',
        value: '3',
      },
      {
        label: '待报废',
        value: '4',
      },
      {
        label: '精仪降档',
        value: '8',
      },
      {
        label: '其他',
        value: '9',
      },
      {
        label: '校外调入',
        value: 'A',
      },
      {
        label: '校内调入',
        value: 'B',
      },
      {
        label: '盘亏',
        value: 'E',
      },
    ],
  },
  {
    label: '学科领域',
    value: 8,
    children: [
      {
        label: '数学',
        value: '1',
      },
      {
        label: '力学',
        value: '2',
      },
      {
        label: '物理学',
        value: '3',
      },
      {
        label: '化学',
        value: '4',
      },
      {
        label: '通讯',
        value: '5',
      },
      {
        label: '生物学',
        value: '6',
      },
    ],
  },
];

const InDataCom = props => {
  const [isLoading, setIsLoading] = useState(false);
  const [loading, SetLoading] = useState(false);
  const [curpage, Setcur] = useState(1);
  const [total, SetTotal] = useState(0);
  const [tableData, SetTableData] = useState([]);
  const [number, Setnumber] = useState(0);
  const [curSize, SetSize] = useState(25);
  const [formList, SetFormList] = useState([]);
  const [form] = Form.useForm();
  const [outRepoter, SetRepoter] = useState([]);
  const [InfoModal, SetInfoMoadl] = useState(false);
  const [columns, Setcolumns] = useState([]);
  const childRef = useRef();
  const [curInfo, SetCurInfo] = useState({
    YQBH: -1,
  });

  let username = useSelector(selectUser);
  useEffect(() => {
    SetLoading(true);
    let temp = [
      {
        title: '仪器编号',
        dataIndex: 'YQBH',
        fixed: 'left',
        width: '80px',
      },
      {
        title: '图片',
        fixed: 'left',
        width: '200px',
        render: (_, record) => {
          return (
            <>
              <Image style={{ width: '200px', height: '100px' }} src={record.imgUrl}></Image>
            </>
          );
        },
      },
      {
        title: '仪器名称',
        dataIndex: 'YQMC',
        fixed: 'left',
        width: '150px',
      },
      {
        title: '金额',
        width: '150px',
        render: (_, record) => {
          return <>{record.JE}元</>;
        },
      },
      {
        title: '收费标准',
        width: '150px',
        render: (_, record) => {
          return <>{record.SFBZ} 元每小时</>;
        },
      },
      {
        title: '学科领域',
        width: '150px',
        render: (_, record) => {
          return <>{XKLYmap.get(record.XKLY)}</>;
        },
      },
      {
        title: '批量',
        width: '150px',
        dataIndex: 'PL',
      },
      {
        title: '购置日期',
        width: '150px',
        dataIndex: 'GZRQ',
      },
      {
        title: '开放时间',
        width: '150px',
        render: (_, record) => {
          return (
            <>
              {record.KFKSSJ}——{record.KFJSSJ}
            </>
          );
        },
      },
      {
        title: '经费科目',
        width: '150px',
        render: (_, record) => {
          return <>{JFKMmap.get(record.JFKM)}</>;
        },
      },
      {
        title: '现状',
        width: '150px',
        render: (_, record) => {
          return <>{XZmap.get(record.XZ)}</>;
        },
      },
      {
        title: '使用方向',
        width: '150px',
        render: (_, record) => {
          return <>{SYFXmap.get(record.SYFX)}</>;
        },
      },
      {
        title: '共享模式',
        width: '150px',
        render: (_, record) => {
          return <>{GXMSmap.get(record.GXMS)}</>;
        },
      },
      {
        title: '联系方式',
        width: '150px',
        render: (_, record) => {
          return <>{record.LXFS}</>;
        },
      },
    ];
    if (props.type == 1) {
      temp.push({
        title: '操作',
        width: '150px',
        fixed: 'right',
        render: (_, record) => {
          if (record.modelUrl === undefined) {
            return <>暂无仪器模型</>;
          }
          return (
            <>
              <Link to={`/pages/ModelPlay/${record.modelUrl}`}>模型浏览</Link>
            </>
          );
        },
      });
    }
    Setcolumns(temp);
    axios
      .post(Config.baseURL + '/instrument/getPassInstrument', {
        curpage: 1,
        pageSize: 25,
        condition: [],
      })
      .then(res => {
        let data = res.data;
        if (res.data.code == 1) {
          Setcur(data.data.cur);
          SetTotal(data.data.total);
          SetTableData(data.data.instrumentList);
          SetLoading(false);
        } else if (res.data.code >= 10000) {
          message.error('错误信息 ' + res.data.message);
          SetLoading(false);
        }
      })
      .catch(err => {
        console.log(err);
        SetLoading(false);
      });
  }, []);
  function onChange(pageNumber, pSize) {
    SetLoading(true);
    SetSize(pSize);
    let data = form.getFieldsValue();
    let arr = [];
    for (let i in data) {
      if (data[i].condition !== undefined) arr.push(data[i]);
    }
    axios
      .post(Config.baseURL + '/instrument/getPassInstrument', {
        curPage: pageNumber,
        pageSize: pSize,
        condition: arr,
      })
      .then(res => {
        let data = res.data;
        if (res.data.code == 1) {
          console.log(data.data);
          Setcur(data.data.cur);
          SetTotal(data.data.total);
          SetLoading(false);
          SetTableData(data.data.instrumentList);
        } else if (res.data.code >= 10000) {
          SetLoading(false);
        }
      })
      .catch(err => {
        console.log(err);
        SetLoading(false);
      });
  }

  const submit = async () => {
    try {
      await form.validateFields();
      let data = form.getFieldsValue();
      let arr = [];
      for (let i in data) {
        if (data[i].condition !== undefined) arr.push(data[i]);
      }
      SetLoading(true);
      axios
        .post(Config.baseURL + '/instrument/getPassInstrument', {
          curPage: 1,
          pageSize: curSize,
          condition: arr,
        })
        .then(res => {
          let data = res.data;
          if (res.data.code == 1) {
            console.log(data.data);
            Setcur(data.data.cur);
            SetTotal(data.data.total);
            SetLoading(false);
            SetTableData(data.data.instrumentList);
          } else if (res.data.code >= 10000) {
            SetLoading(false);
          }
        })
        .catch(err => {
          console.log(err);
          SetLoading(false);
        });
    } catch (err) {
      console.log(err);
    }
  };
  const rowSelectionChange = (keys, rows) => {
    SetRepoter(rows);
  };
  const generateDocument = () => {
    let time = moment().format('YYYY-MM-DD HH:mm:ss');
    for (let i = 0; i < outRepoter.length; i++) {
      let temp = outRepoter[i];
      temp.XKLY = XKLYmap.get(temp.XKLY);
      temp.JFKM = JFKMmap.get(temp.JFKM);
      temp.XZ = XZmap.get(temp.XZ);
      temp.SYFX = SYFXmap.get(temp.SYFX);
      temp.GXMS = GXMSmap.get(temp.GXMS);
      loadFile(
        'https://instrumentsys.oss-cn-beijing.aliyuncs.com/template/repoterTemplate.docx',
        (error, content) => {
          if (error) {
            throw error;
          }
          const zip = new PizZip(content);
          const doc = new Docxtemplater(zip, {
            paragraphLoop: true,
            linebreaks: true,
          });

          doc.render({
            ...temp,
            time: time,
            name: username,
          });
          const out = doc.getZip().generate({
            type: 'blob',
            mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          });
          saveAs(out, temp.YQBH + '_' + temp.YQMC + '_仪器信息');
        }
      );
    }
  };
  const generateExcel = () => {
    let excelData = [];
    let head = [
      '仪器编号',
      '仪器名称',
      '金额',
      '收费标准',
      '学科领域',
      '批量',
      '购置日期',
      '开放开始时间',
      '开放结束时间',
      '经费科目',
      '现状',
      '使用方向',
      '共享模式',
      '联系方式',
      '主要功能',
      '样品要求',
      '技术指标',
      '预约说明',
      '测试说明',
      '备注',
    ];
    excelData.push(head);
    for (let i = 0; i < outRepoter.length; i++) {
      let temp = [];
      temp.push(outRepoter[i].YQBH);
      temp.push(outRepoter[i].YQMC);
      temp.push(outRepoter[i].JE);
      temp.push(outRepoter[i].SFBZ);
      temp.push(XKLYmap.get(outRepoter[i].XKLY));
      temp.push(outRepoter[i].PL);
      temp.push(outRepoter[i].GZRQ);
      temp.push(outRepoter[i].KFKSSJ);
      temp.push(outRepoter[i].KFJSSJ);
      temp.push(JFKMmap.get(outRepoter[i].JFKM));
      temp.push(outRepoter[i].XZ);
      temp.push(SYFXmap.get(outRepoter[i].SYFX));
      temp.push(GXMSmap.get(outRepoter[i].GXMS));
      temp.push(outRepoter[i].LXFS);
      temp.push(outRepoter[i].ZYGN);
      temp.push(outRepoter[i].YPYQ);
      temp.push(outRepoter[i].JSZB);
      temp.push(outRepoter[i].YYSM);
      temp.push(outRepoter[i].CSSM);
      temp.push(outRepoter[i].BZ);
      excelData.push(temp);
    }
    let excel = XLSX.utils.aoa_to_sheet(excelData);
    openDownloadDialog(sheet2blob(excel), '仪器信息.xlsx');
  };
  const deleteIn = () => {
    SetLoading(true);
    let instrumentIdList = [];
    let inNameList = [];
    console.log(outRepoter);
    for (let val of outRepoter) {
      instrumentIdList.push(val.YQBH);
      inNameList.push(val.YQMC);
    }
    axios
      .post(Config.baseURL + '/instrument/deleteInstrument', {
        instrumentIdList: instrumentIdList,
        inNameList: inNameList,
        username: username,
        time: moment().format('YYYY-MM-DD HH:mm:ss'),
      })
      .then(res => {
        let data = res.data;
        if (res.data.code == 1) {
          message.success('提交删除申请成功');
          SetLoading(false);
        } else if (res.data.code >= 10000) {
          message.error('错误信息 ' + res.data.message);
          SetLoading(false);
        }
      })
      .catch(err => {
        console.log(err);
        SetLoading(false);
      });
  };
  const editIn = () => {
    if (outRepoter.length == 0) {
      message.error('请选择要编辑的仪器', 2);
      return;
    }
    console.log(outRepoter[0]);
    SetCurInfo(outRepoter[0]);
    SetInfoMoadl(true);
    console.log(childRef);
    childRef.current.SetReFresh(!childRef.current.refresh);
  };
  const Edit = () => {
    const getval = async () => {
      let val = await childRef.current.editFormValue();
      console.log(val);
      axios
        .post(Config.baseURL + '/instrument/instrumentEdit', {
          ...val,
          YQBH: curInfo.YQBH,
          username: username,
          time: moment().format('YYYY-MM-DD HH:mm:ss'),
        })
        .then(res => {
          if (res.data.code == 1) {
            message.success('申请修改成功', 2, () => {
              setIsLoading(false);
            });
          } else if (res.data.code >= 10000) {
            console.log(res.data.data);
            message.error('申请修改失败，原因：' + res.data.message, 2, () => {
              setIsLoading(false);
            });
          }
        })
        .catch(err => {
          message.error('申请修改失败，原因：' + err, 2, () => {
            setIsLoading(false);
          });
        });
    };
    getval();
  };

  return (
    <>
      <Layout>
        <Header
          style={{
            borderRadius: '5px 5px 0px 0px',
            height: '40px',
            padding: '0px 15px',
            margin: '0px 0px',
            backgroundColor: 'white',
            textAlign: 'left',
            lineHeight: '40px',
          }}
        >
          <h3>查询条件</h3>
        </Header>
        <Content style={{ padding: '10px 20px', backgroundColor: 'white' }}>
          <Row>
            <Col span={6}>
              <Row>
                <Col span={8}>
                  <h3 style={{ margin: '0' }}>条件数量：</h3>
                </Col>
                <Col span={16}>
                  <Button
                    style={{ border: '0' }}
                    size="large"
                    icon={<MinusCircleOutlined />}
                    onClick={() => {
                      if (number == 0) return;
                      Setnumber(number - 1);
                      let newarr = formList.slice(0, formList.length - 1);
                      SetFormList(newarr);
                    }}
                  />
                  {number}
                  <Button
                    style={{ border: '0' }}
                    size="large"
                    icon={<PlusCircleOutlined />}
                    onClick={() => {
                      Setnumber(number + 1);
                      SetFormList([...formList, number + 1]);
                    }}
                  />
                </Col>
              </Row>
            </Col>
            <Col span={2}>
              <Button type="primary" size="large" onClick={submit}>
                查询
              </Button>
            </Col>
          </Row>

          <Form style={{ marginTop: '20px' }} form={form}>
            <Row>
              {formList.map((val, index) => {
                return (
                  <>
                    <Col span={6}>
                      <Form.Item
                        style={{ width: '350px' }}
                        rules={[
                          {
                            required: true,
                            message: '请选择条件',
                          },
                        ]}
                        label="查询条件"
                        name={[index, 'condition']}
                      >
                        <Cascader options={options} placeholder="请选择字段及条件" />
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Form.Item
                        label="查询参数"
                        style={{ folat: 'left', width: '180px' }}
                        name={[index, 'val']}
                      >
                        <Input style={{}}></Input>
                      </Form.Item>
                    </Col>
                  </>
                );
              })}
            </Row>
          </Form>
        </Content>
      </Layout>
      <Layout style={{ marginTop: '40px' }}>
        <Header
          style={{
            borderRadius: '5px 5px 0px 0px',
            height: '40px',
            padding: '0px 15px',
            margin: '0px 0px',
            backgroundColor: 'white',
            textAlign: 'left',
            lineHeight: '40px',
          }}
        >
          <h3>仪器信息</h3>
        </Header>
        <Spin spinning={loading}>
          <Content style={{ padding: '10px 20px', backgroundColor: 'white' }}>
            <Row>
              <Col span={12}>
                <Pagination
                  style={{ float: 'left' }}
                  showQuickJumper
                  defaultCurrent={curpage}
                  total={total}
                  defaultPageSize={25}
                  onChange={onChange}
                  showTotal={total => `总共 ${total} 条结果`}
                />
              </Col>
              <Col span={12}>
                <Button
                  type="primary"
                  size="large"
                  icon={<FileWordOutlined />}
                  onClick={generateDocument}
                  style={{ display: props.type == 1 ? 'inline' : 'none' }}
                >
                  生成仪器报表
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: '20px', display: props.type == 1 ? 'inline' : 'none' }}
                  size="large"
                  onClick={generateExcel}
                  icon={<FileExcelOutlined />}
                >
                  导出excel表格
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: '20px', display: props.type == 3 ? 'inline' : 'none' }}
                  size="large"
                  onClick={deleteIn}
                  icon={<DeleteOutlined />}
                >
                  删除仪器
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: '20px', display: props.type == 2 ? 'inline' : 'none' }}
                  size="large"
                  onClick={editIn}
                  icon={<SnippetsOutlined />}
                >
                  修改仪器
                </Button>
              </Col>
            </Row>
            <Table
              scroll={{ x: 1500, y: 600 }}
              bordered
              rowKey="YQBH"
              rowSelection={{
                fixed: 'left',
                onChange: rowSelectionChange,
                type: props.type == 2 ? 'radio' : 'checkbox',
              }}
              expandable={{
                expandedRowRender: record => {
                  return (
                    <Descriptions bordered>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="主要功能">
                        {record.ZYGN}
                      </Descriptions.Item>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="样品要求">
                        {record.YPYQ}
                      </Descriptions.Item>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="技术指标">
                        {record.JSZB}
                      </Descriptions.Item>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="预约说明">
                        {record.YYSM}
                      </Descriptions.Item>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="测试说明">
                        {record.CSSM}
                      </Descriptions.Item>
                      <Descriptions.Item style={{ backgroundColor: 'white' }} label="备注">
                        {record.BZ}
                      </Descriptions.Item>
                    </Descriptions>
                  );
                },
              }}
              columns={columns}
              dataSource={tableData}
              style={{ marginTop: '20px' }}
              pagination={false}
            ></Table>
          </Content>
        </Spin>
      </Layout>
      <Modal
        title="仪器审核"
        visible={InfoModal}
        onCancel={() => {
          SetInfoMoadl(false);
        }}
        footer={null}
        width={1653}
        style={{ top: 20 }}
      >
        <Row
          style={{
            borderBottom: '3px solid #1890FF',
            height: '500px',
            overflow: 'auto',
            overflowX: 'hidden',
          }}
        >
          <Col span={24}>
            <InstrumentCard
              disable={curInfo.taskName != '仪器修改' && props.type != 2}
              curInfo={curInfo}
              SetCurInfo={SetCurInfo}
              ref={childRef}
            ></InstrumentCard>
          </Col>
        </Row>
        <Row style={{ marginTop: '20px', height: '25px' }}>
          <Col span={12}></Col>
          <Col span={8}></Col>
          <Col style={{ textAlign: 'center' }} span={4}>
            <Button
              style={{ marginRight: '15px' }}
              danger
              type="primary"
              size="large"
              loading={isLoading}
              onClick={() => {
                SetInfoMoadl(false);
              }}
            >
              放弃
            </Button>
            <Button onClick={Edit} loading={isLoading} type="primary" size="large">
              提交
            </Button>
          </Col>
        </Row>
      </Modal>
    </>
  );
};

export default InDataCom;
